# -*- coding: UTF-8 -*-
"""
@Project ：swift-forge-engine
@File    ：access_middle.py
@IDE     ：PyCharm 
@Author  ：Tony.Gan
@Date    ：2025/1/19 18:01 
@Des     ：
"""
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint

from App.utils.timezone import timezone
from App.config.log_conf import log


class AccessMiddleware(BaseHTTPMiddleware):
    """请求日志中间件"""

    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
        start_time = timezone.now()
        response = await call_next(request)
        end_time = timezone.now()
        log.info(
            f'{request.client.host: <15}|{request.method: <8}|{response.status_code: <6}|'
            f'{request.url} |{round((end_time - start_time).total_seconds(), 3) * 1000.0}ms'
        )
        return response
